package com.jt.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration //标识我是一个配置类
@PropertySource("classpath:/properties/redis.properties")
public class JedisConfig {

    @Value("${redis.nodes}")
    private String nodes; //node,node,node

    @Bean //实例化集群的对象之后交给Spring容器管理
    public JedisCluster jedisCluster(){
        Set<HostAndPort> set = new HashSet<>();
        String[] nodeArray = nodes.split(",");
        for(String node : nodeArray){ //host:port
            String[] nodeTemp = node.split(":");
            String host = nodeTemp[0];
            int port = Integer.parseInt(nodeTemp[1]);
            HostAndPort hostAndPort = new HostAndPort(host, port);
            set.add(hostAndPort);
        }
        return new JedisCluster(set);
    }











   /* @Value("${redis.nodes}")
    private String nodes; //node,node,node
    *//**
     * 添加Redis分片的配置
     * 需求1: 动态的获取IP地址/PORT端口
     *        动态的获取多个的节点信息. 方便以后扩展
     *//*
    @Bean
    public ShardedJedis shardedJedis(){
        List<JedisShardInfo> list = new ArrayList<>();
        String[] strArray = nodes.split(","); //[node,node,node]
        for (String node : strArray){  //ip:port
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            list.add(new JedisShardInfo(host,port ));
        }
        return new ShardedJedis(list);
    }
*/




   /* @Value("${redis.host}") //spel表达式  yml为准
    private String  host;
    @Value("${redis.port}")
    private Integer port;
    *//**
     * 将jedis对象交给spring容器管理
     *//*
    @Bean   //默认条件下是单例对象
    //@Scope("prototype") //设置为多利对象
    public Jedis jedis(){
        //由于将代码写死不利于扩展,所以将固定的配置添加到配置文件中
        return new Jedis(host,port);
    }*/
}
